#include "stdafx.h"
#include "FileOps.h"

#include "Generators.h"

void WriteBinaryFile(std::string dataFileName, AC::BlockData<BLOCK_LEN>& data)
{
	WriteBinaryFile(dataFileName, data.Get());
};

void WriteBinaryFile(std::string dataFileName, AC::Block<BLOCK_LEN>& data)
{
	WriteBinaryFile(dataFileName, data.Get());
};

void WriteBinaryFile(std::string dataFileName, std::vector<byte>& data)
{
	std::ofstream file(dataFileName.c_str(), std::ios::binary | std::ios::out);

	if(!file.is_open())
		return;

	for(unsigned int i = 0; i < data.size(); i++)
		file.write((const char*)&data[i], sizeof(byte));

	file.close();
};

void AppendBinaryFile(std::string dataFileName, AC::BlockData<BLOCK_LEN>& data)
{
	AppendBinaryFile(dataFileName, data.Get());
};

void AppendBinaryFile(std::string dataFileName, AC::Block<BLOCK_LEN>& data)
{
	AppendBinaryFile(dataFileName, data.Get());
};

void AppendBinaryFile(std::string dataFileName, std::vector<byte>& data)
{
	std::ofstream file(dataFileName.c_str(), std::ios::binary | std::ios::app);

	if(!file.is_open())
		return;

	for(unsigned int i = 0; i < data.size(); i++)
		file.write((const char*)&data[i], sizeof(byte));

	file.close();
};

AC::BlockData<BLOCK_LEN> ReadBinaryFile(std::string dataFileName)
{
	AC::HexParser Ox;
	std::ifstream dataFile(dataFileName.c_str(), std::ios::binary | std::ios::in);
	int length;
	char* buffer;
	AC::BlockData<BLOCK_LEN> empty;

	if(!dataFile.is_open())
		return empty;

	dataFile.seekg(0, std::ios::end);
	length = dataFile.tellg();
	dataFile.seekg(0, std::ios::beg);

	buffer = new char[length];

	dataFile.read(buffer, length);
	dataFile.close();

	std::vector<byte> vdata(buffer, buffer + length * sizeof(byte) );
	AC::BlockData<BLOCK_LEN> data(vdata);

	delete [] buffer;

	return data;
};

AC::AES::Key<KEY_LEN> ReadKeyFile(std::string keyFileName)
{
	AC::HexParser Ox;
	std::ifstream keyFile(keyFileName.c_str(), std::ios::binary | std::ios::in);
	int length;
	char* buffer;
	AC::AES::Key<KEY_LEN> key;

	if(!keyFile.is_open())
		return key;

	keyFile.seekg(0, std::ios::end);
	length = keyFile.tellg();
	keyFile.seekg(0, std::ios::beg);

	buffer = new char[length+1];

	keyFile.read(buffer, length);
	keyFile.close();
	buffer[length] = '\0';

	key.Set(Ox(buffer));

	delete [] buffer;

	return key;
};
